package wind

import (
	"database/sql"
	"sync"

	"gitee.com/tinkler/yunfei/ws"
	"gitee.com/tinkler/yunfei/ws/arsenal"
	"gitee.com/tinkler/yunfei/ws/forge"
)

var (
	sheathMu sync.RWMutex
	sheaths  = make(map[string]*Sheath)
)

func init() {
	scabbard := Scabbard{}
	ws.ForgeScabbard("wind", &scabbard)
}

type Scabbard struct{}

func (s Scabbard) NewSheath(name string, config forge.YamlConf) arsenal.Sheath {
	sheathMu.Lock()
	defer sheathMu.Unlock()
	if name == "" {
		panic("ws:Scabbard name is nil")
	}
	if _, dup := sheaths[name]; dup {
		panic("ws:Forge called twice for scabbard " + name)
	}
	sh := Sheath{
		mem: make(forge.MemDB),
		c:   &SheathConf{},
	}
	sheaths[name] = &sh

	//DB
	pg, err := sql.Open("postgres", config.PgConf.GetDatasource())
	if err != nil {
		panic("ws: When open postgresql got error")
	}
	sh.db = pg
	return sh
}

func (s Scabbard) SetError(message string) forge.Response {
	res := forge.Response{
		Status:  0,
		Message: message,
		Data:    nil,
	}
	return res
}
